package top.hmtools.jsCss.jsManager;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import top.hmtools.base.StringTools;
import top.hmtools.jsCss.autoConfiguration.JsCssAutoConfiguration;
import top.hmtools.jsCss.common.CommonTools;
import top.hmtools.jsCss.common.ResourcesBean;

/**
 * 缺省的javascript文件管理者
 * @author HyboJ
 * 创建日期：2017-9-26下午9:42:56
 */
@Component
//@ConditionalOnBean(IsEnableJsCss.class)
public class JavascriptManagerDefault implements IJavascriptManager{
	
	protected final Logger logger = LoggerFactory.getLogger(JavascriptManagerDefault.class);
	
	@Autowired
	private JsCssAutoConfiguration jsCssAutoConfiguration;
	
	/**
	 * javascript文件缓存库
	 */
	private static Map<String, ResourcesBean> JS_REPERTORY = new HashMap<String, ResourcesBean>();
	
	private String encoding = "UTF-8";

	@Override
	@PostConstruct
	public void init() {
		//初始化文件路径集合与文件编码格式，用于刷新
		String jsFilesPathStr = this.jsCssAutoConfiguration.getJsFilesPaths();
		this.logger.info("监控js的磁盘路径有：{}",jsFilesPathStr);
		String[] pathsArr = jsFilesPathStr.split(",");
		
		this.encoding = this.jsCssAutoConfiguration.getEncoding();
		String[] extensions = {"js","JS"}; 
		
		//尝试加载当前运行工程classpath中的javascript文件
		for(String dir:pathsArr){
		    try {
		        Enumeration<URL> resources = CommonTools.getURLs(dir);
		        CommonTools.loadContent(encoding,dir, resources, JS_REPERTORY,extensions);
		    } catch (IOException e1) {
		        this.logger.error("尝试从classpath中加载资源失败："+e1.getMessage(),e1);
		    }
		}
		
		this.logger.info("当前成功加载javascript文件总条数是：{}",JS_REPERTORY.size());
	}

	@Override
	@PreDestroy
	public void destory() {
		if(JS_REPERTORY != null){
			JS_REPERTORY.clear();
		}
	}

	@Override
	public String getJs(String jsNames) {
		if(jsNames != null && !"".equals(jsNames)){
			String[] jsNamesArr = jsNames.split(",");
			return this.getJs(jsNamesArr);
		}else{
			return ";";
		}
	}

	@Override
	public String getJs(List<String> jsNames) {
		if(jsNames != null && jsNames.size()>0){
			String[] jsNamesArr = jsNames.toArray(new String[0]);
			return this.getJs(jsNamesArr);
		}else{
			return ";";
		}
	}

	@Override
	public String getJs(String[] jsNames) {
		StringBuffer sb_result = new StringBuffer(";");
		if(jsNames != null && jsNames.length>0){
			for(String fileName:jsNames){
				String js_content_tmp = this.getOneJsContent(fileName);
				if(js_content_tmp == null || "".equals(js_content_tmp)){
					continue;
				}
				sb_result.append(js_content_tmp+";");
			}
			return sb_result.toString();
		}else{
			return ";";
		}
	}
	
	/**
	 * 获取单个js文件内容
	 * @param keyWord
	 * @return
	 */
	private String getOneJsContent(String keyWord){
		String result = null;
		//检查入参
		if(keyWord == null || keyWord.trim().length()<=0){
			return result;
		}
		
		//key统一为小写字母
		keyWord = keyWord.trim().toLowerCase();
		
		//key统一使用“.js”后缀结尾
		if(!keyWord.endsWith(".js")){
			keyWord=keyWord+".js";
		}
		
		//获取仓库中所有索引名称
		List<String> filenames = this.listJsFilenames();
		
		//以后缀是否匹配为条件检索
		for(String filename:filenames){
			if(filename.endsWith(keyWord)){
				ResourcesBean resourcesBean = JS_REPERTORY.get(filename);
				result = "\r\n/**  file :: "+resourcesBean.getFileRelativePath()+" :: start **/\r\n"+resourcesBean.getFileContent() + "\r\n/**  file :: "+resourcesBean.getFileRelativePath()+" :: end **/\r\n";
			}
		}
		return result;
	}

	@Override
	public boolean refresh() {
		boolean result = false;
		try {
			this.destory();
			this.init();
			result=true;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return result;
	}

	@Override
	public List<String> listJsFilenames() {
		List<String> result = new ArrayList<String>();
		if(JS_REPERTORY != null){
			Set<String> keySet = JS_REPERTORY.keySet();
			result.addAll(keySet);
			Collections.sort(result);
		}
		return result;
	}

	@Override
	public List<ResourcesBean> listResourcesBeans() {
		ArrayList<ResourcesBean> result = new ArrayList<ResourcesBean>();
		if(JS_REPERTORY!=null){
			Collection<ResourcesBean> values = JS_REPERTORY.values();
			result.addAll(values);
			//按基本文件名的字典排序
			Collections.sort(result, new Comparator<ResourcesBean>(){

				@Override
				public int compare(ResourcesBean aa, ResourcesBean bb) {
					String aaName = aa.getFileBaseName();
					String bbName = bb.getFileBaseName();
					if(StringTools.isAnyBlank(aaName,bbName)){
						return 0;
					}
					List<String> tmp = new ArrayList<>();
					tmp.add(aaName);
					tmp.add(bbName);
					Collections.sort(tmp);//字典序
					boolean isUnResorted = tmp.get(0).equals(aaName);
					if(isUnResorted){
						return -1;
					}else{
						return 1;
					}
				}
				
			});
		}
		return result;
	}

}
